<template>
  <view>
    <u-navbar title="巡检详情" :background="{ backgroundColor:'#9CE0FF'}" :border-bottom="false" title-color="#000" title-size="37" />
    <canvas
      class="w-full"
      id="container"
      :style="{height:`calc(100vh - ${top}px)`}"
      canvas-id="mycanvas"
      @touchstart="touchstart"
      @touchmove="touchmove"
      @touchend="touchend" >
    </canvas>
    <canvas
      v-show="showRotateCanvas"
      canvas-id="rotateCanvas"
      class="absolute top-99999"
      :style="{width:windowHeight +'px',height:windowWidth +'px'}"
    >
    </canvas>
    <cover-view class="flex absolute btns">
<!--      <cover-view class="lh-60 text-center w-120 br-5 border-2D8CF0 color-2D8CF0 fz-28 mr-20" @tap.stop="choose">选择</cover-view>-->
      <cover-view class="lh-60 text-center w-120 br-5 border-2D8CF0 color-2D8CF0 fz-28 mr-20" @tap.stop="cancle">取消</cover-view>
      <cover-view class="lh-60 text-center w-200 br-5 border-2D8CF0 color-2D8CF0 fz-28 mr-20" @tap.stop="clearfunction">清除签名板</cover-view>
      <cover-view class="lh-60 text-center w-175 br-5 border-2D8CF0 color-fff bg-2D8CF0 fz-28" @tap.stop="finish">确认签名</cover-view>
    </cover-view>

    <!--异常提示模态框-->
    <cover-view class="fixed top0 w-full min-100vh bg-00000060 flex align-center justify-center z-999" v-show="isModalShow" @click="isModalShow = false">
      <cover-view class="h-200 w-600  br-20 flex align-center justify-center bg-fff fz-30 font-bold color-333333">
        <cover-image class="mr-20 w-38 h-38" src="@/static/images/mine/error.png"></cover-image>
        <cover-view>{{modalContent}}</cover-view>
      </cover-view>
    </cover-view>

    <!--图片上传提示模态框-->
    <cover-view class="fixed top0 w-full min-100vh bg-00000060 flex align-center justify-center z-999" v-show="loading">
      <cover-view class="h-200 w-600 br-20 text-center lh-200 font-bold color-888888 lh-33 bg-fff">
        图片上传中
      </cover-view>
    </cover-view>
  </view>
</template>

<script>
import config from '@/config';
import { workOrderSignature, queryHistorySign } from '@/api/inspection/sign';
export default {

  data() {
    return {
      ctx: '', //绘图图像
      points: [], //路径点集合
      value:'',
      windowWidth:0,
      windowHeight:0,
      workOrderId: '',
      ossId: '',
      imgUrl: '',
      top:0,
      timer: [],
      showRotateCanvas: false,
      isModalShow: false,
      modalContent: '',
      loading: false,
    }
  },
  mounted() {
    const query = uni.createSelectorQuery().in(this);
    query.select('#container').boundingClientRect(data => {
      this.top = data.top
      uni.getSystemInfo({
        success: res => {
          this.windowWidth = res.windowWidth;
          this.windowHeight = res.windowHeight - data.top;
          this.showRotateCanvas = true
        },
      })
      this.checkImg()
    }).exec();
    this.ctx = uni.createCanvasContext("mycanvas", this); //创建绘图对象
    this.ctx.setFillStyle('#fff')
    //设置画笔样式
    this.ctx.lineWidth = 4;
    this.ctx.lineCap = "round"
    this.ctx.lineJoin = "round"
  },
  onLoad(option) {
    this.workOrderId = option.workOrderId
  },
  methods: {
    //查询工单签名
    checkImg() {
      queryHistorySign().then(res => {
        this.ossId = res.data.ossId || ''
        this.imgUrl = res.data.url || ''
        if(this.ossId && this.imgUrl) {
          uni.getImageInfo({
            src: this.imgUrl,
            success: (img) => {
              const ctx2 = uni.createCanvasContext('rotateCanvas',this);
              ctx2.drawImage(img.path, 0, 0, this.windowHeight, this.windowWidth)
              ctx2.draw(false,()=>{
                //使用setTimeout防止图片过大或者手机性能过低导致canvas没画完就导出图片报错
                this.timer.push(setTimeout(()=>{
                  uni.canvasToTempFilePath({
                    canvasId: 'rotateCanvas',
                    success: res => {
                      this.ctx.translate(this.windowWidth,0);
                      this.ctx.rotate(90 * Math.PI / 180)
                      this.ctx.drawImage(res.tempFilePath, 0, 0, this.windowHeight, this.windowWidth)
                      this.ctx.draw(true)
                      this.ctx.rotate(-90 * Math.PI / 180)
                      this.ctx.translate(-this.windowWidth,0);
                    },
                    fail: (err) => {
                      console.log('fail', err)
                    }
                  },this)
                },500))
              })
            },
            fail: function(err) {
              console.log('getImageInfoErr',err)
            },
          })
        }
      })
    },
    choose(){
      uni.chooseImage({
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          this.ctx.drawImage(tempFilePath,0,0,this.windowWidth,this.windowHeight)
          this.ctx.draw(true)
        },
      });
    },
    //触摸开始，获取到起点
    touchstart(e) {
      if(this.ossId) return
      let startX = e.changedTouches[0].x;
      let startY = e.changedTouches[0].y;
      let startPoint = {
        X: startX,
        Y: startY
      };

      /* **************************************************
          #由于uni对canvas的实现有所不同，这里需要把起点存起来
       * **************************************************/
      this.points.push(startPoint);

      //每次触摸开始，开启新的路径
      this.ctx.beginPath();
    },

    //触摸移动，获取到路径点
    touchmove(e) {
      let moveX = e.changedTouches[0].x;
      let moveY = e.changedTouches[0].y;
      let movePoint = {
        X: moveX,
        Y: moveY
      };
      this.points.push(movePoint); //存点
      if (this.points.length >= 2) {
        this.draw(); //绘制路径
      }
    },

    // 触摸结束，将未绘制的点清空防止对后续路径产生干扰
    touchend() {
      this.points = [];
    },

    /* ***********************************************
    #   绘制笔迹
    #   1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
    #   2.为保证笔迹连续，每次从路径集合中取两个点作为起点（moveTo）和终点(lineTo)
    #   3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
    ************************************************ */
    draw() {
      let point1 = this.points[0]
      let point2 = this.points[1]
      this.points.shift()
      this.ctx.moveTo(point1.X, point1.Y)
      this.ctx.lineTo(point2.X, point2.Y)
      this.ctx.stroke()
      this.ctx.draw(true)
    },

    //清空画布
    clearfunction() {
      this.ctx.setFillStyle('#fff')
      this.ctx.clearRect(0, 0, this.windowWidth, this.windowHeight);
      this.ctx.draw(true);
    },

    //完成绘画并保存到本地
    finish: function() {
      this.loading = true
      let that = this
      //使用setTimeout防止图片过大或者手机性能过低导致canvas没画完就导出图片报错
      this.timer.push(setTimeout(()=>{
        uni.canvasToTempFilePath({
          canvasId: 'mycanvas',
          success: res => {
            const ctx2 = uni.createCanvasContext('rotateCanvas',this);
            ctx2.translate(0, this.windowWidth);
            ctx2.rotate(-90 * Math.PI / 180)
            ctx2.drawImage(res.tempFilePath, 0, 0, this.windowWidth, this.windowHeight)
            ctx2.draw()
            this.timer.push(setTimeout(()=> {
              //使用第二个canvas旋转图片
              uni.canvasToTempFilePath({
                width: that.windowHeight,
                height: that.windowWidth,
                destHeight: that.windowHeight,
                destWidth: that.windowWidth,
                fileType: 'png',
                canvasId: 'rotateCanvas',
                success: function (res) {
                  // uni.saveImageToPhotosAlbum({
                  //   filePath: res.tempFilePath
                  // })
                  that.imgUpload(res.tempFilePath).then(res => {
                    that.getWorkOrderSignature(res)
                  })
                },
                fail: (err) => {
                  console.log('fail', err)
                  this.isModalShow = true
                  this.modalContent = '图片上传失败'
                  this.loading = false
                }
              },that)
            }, 500))
          },
          fail: function(err) {
            console.log('mycanvas',err)
            this.isModalShow = true
            this.modalContent = '图片上传失败'
            this.loading = false
          },
        },that)
      },500))

    },

    imgUpload(tempFilePaths) {
      let ossId = '';
      return new Promise((resolve, reject) => {
        const uploadTask = uni.uploadFile({
          url: config.baseUrl + '/system/oss/upload',
          filePath: tempFilePaths,
          name: 'file',
          header: {
            Authorization: 'Bearer ' + this.$store.getters.token
          },
          success: (uploadFileRes) => {
            const data = JSON.parse(uploadFileRes.data)
            if(data.data.ossId) {
              ossId = data.data.ossId
              resolve(ossId)
            }
          },
          fail: (err) => {
            if(err.errMsg.indexOf('timeout') > -1){
              this.isModalShow = true
              this.modalContent = '网络超时'
            }
            else{
              this.isModalShow = true
              this.modalContent = '图片上传失败'
            }
            reject(err);
          },
          complete: () => {
            this.loading = false
          }
        });
      })
    },
    getWorkOrderSignature(id) {
      workOrderSignature({ ossId: `${id}`, workOrderId: this.workOrderId }).then(res => {
        uni.navigateBack()
      })
    },
    cancle(){
      uni.navigateBack()
    }
  },
  beforeDestroy(){
    clearTimeout(this.timer)
  },
}
</script>
<style lang="scss">
page{
  background-color: #FFFFFF;
}
</style>
<style lang="scss" scoped>
.btns{
  transform: rotate(90deg);
  transform-origin: left bottom;
  right: -450rpx;
  bottom: 600rpx;
}
</style>


